<template>
  <div>
    <el-drawer
      :title="$t('message.dxfj')"
      :visible.sync="isShowModal"
      :before-close="handleClose"
      size="920px"
    >
      <el-form
        ref="form"
        class="doumee-form"
        :model="param"
        :rules="rules"
        label-width="auto"
        label-suffix="："
      >
        <div class="warnningTip">
          {{ $t('message.qfdxyc') }}
        </div>
        <el-form-item :label="$t('message.jsdx')" prop="receptionType">
          <el-radio
            v-model="param.receptionType"
            label="1"
            @change="changeReType"
          >{{ $t('message.zdhy') }}</el-radio>
          <el-radio
            v-model="param.receptionType"
            label="2"
            @change="changeReType"
          >{{ $t('message.zdsjh') }}</el-radio>
          <el-radio
            v-model="param.receptionType"
            label="3"
            @change="changeReType"
          >{{ $t('message.zdrq') }}</el-radio>
          <el-radio
            v-model="param.receptionType"
            label="4"
            @change="changeReType"
          >{{ $t('message.qbhy') }}</el-radio>
        </el-form-item>
        <el-form-item
          v-if="param.receptionType != '4'"
          style="margin-top: -20px"
          prop="obj"
        >
          <MemberSearch
            v-if="param.receptionType == '1'"
            @select="memberChange"
            @clear="memberClear"
          />
          <el-input
            v-if="param.receptionType == '2'"
            v-model="param.obj"
            type="textarea"
            :rows="6"
            show-word-limit
            :placeholder="$t('message.srsjhmh1')"
          />
          <div v-if="param.receptionType == '3'" class="portrayal_option">
            <div class="list">
              <div
                v-for="item in portrayalList"
                :key="item.portraitId"
                :class="{ active: item.portraitId === param.obj }"
                class="item"
                @click="portrayalClick(item.portraitId)"
              >
                {{ item.portraitName }}
              </div>
            </div>
            <div v-if="portrayalList.length < 20" class="fs12">
              {{ $t('message.bumanzu') }}，<span
                class="primaryColor pointer"
                @click="goToPortrayal"
              >{{ $t('message.qxzhx') }}</span>
            </div>
          </div>
        </el-form-item>
        <el-form-item :label="$t('message.ffnr')" prop="grantObj">
          <div class="df_ac">
            <el-select
              v-model="param.grantType"
              class="mr10 w100"
              @change="changeType"
            >
              <el-option :label="$t('message.yhj')" value="1" />
              <el-option :label="$t('message.tc')" value="2" />
            </el-select>
            <el-select
              v-if="param.grantType == '2'"
              v-model="param.grantObj"
              multiple
              :multiple-limit="5"
              class="w300"
              filterable
              collapse-tags
              :placeholder="$t('message.qxztzzd5')"
            >
              <el-option
                v-for="item in mealList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
            <el-select
              v-if="param.grantType == '1'"
              v-model="param.grantObj"
              multiple
              :multiple-limit="5"
              class="w300"
              filterable
              collapse-tags
              :placeholder="$t('message.qxzyhjzd5')"
            >
              <el-option
                v-for="item in couponList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
            <div v-if="param.grantType == '1'" class="fs12 ml10">
              {{ $t('message.dxfjbkcsy') }}
            </div>
            <div v-if="param.grantType == '2'" class="fs12 ml10">
              {{ $t('message.dxfjbkctc') }}
            </div>
          </div>
        </el-form-item>
        <el-form-item :label="$t('message.dxtz')">
          <el-radio
            v-model="param.isSendMsg"
            label="0"
            @change="changeSms"
          >{{ $t('message.bfsdx') }}</el-radio>
          <el-radio
            v-model="param.isSendMsg"
            label="1"
            @change="changeSms"
          >{{ $t('message.fsdxtz') }}</el-radio>
        </el-form-item>
        <el-form-item
          v-if="param.isSendMsg == '1'"
          :label="$t('message.dxnr')"
          :prop="param.smsType == '1' ? 'smsInfo' : 'smsTempId'"
        >
          <el-radio
            v-model="param.smsType"
            label="1"
            @change="changeSmsType"
          >{{ $t('message.zdynr') }}</el-radio>
          <el-radio
            v-model="param.smsType"
            label="2"
            @change="changeSmsType"
          >{{ $t('message.xzmoban') }}</el-radio>
          <el-select
            v-if="param.smsType == '2'"
            v-model="param.smsTempId"
            filterable
            class="w200"
          >
            <el-option
              v-for="item in smsTemplate"
              :key="item.id"
              :label="item.title"
              :value="item.id"
            />
          </el-select>
          <div class="warnningTip">
            {{ $t('message.dxaqzcjq') }}
          </div>
          <template v-if="param.smsType == '1'">
            <div class="df_sb" style="margin-top: -20px">
              <span>{{ $t('message.dxqm') }}：[{{ shopInfo.smsSign }}]</span>
              <div class="df_ac">
                <el-input
                  v-if="param.isSaveTempId == '1'"
                  v-model="param.tempName"
                  placeholder="$t('message.qsr') + $t('message.mbbt')"
                  class="mr10"
                />
                <el-checkbox
                  v-model="param.isSaveTempId"
                  true-label="1"
                  false-label="0"
                >{{ $t('message.cwmb') }}</el-checkbox>
              </div>
            </div>
            <div class="sms_template">
              <el-input
                id="textareaId"
                v-model="param.smsInfo"
                type="textarea"
                :rows="6"
                maxlength="268"
                show-word-limit
                :placeholder="$t('message.qsrdxnr')"
              />
              <span class="fs12 placeholder9 rr">{{ $t('message.jsqhfr') }}</span>
            </div>
          </template>
        </el-form-item>
        <el-form-item
          v-if="param.smsType == '1' && param.isSendMsg == '1'"
          :label="$t('message.crspf')"
          prop="name"
        >
          <div class="df_ac">
            <el-button
              @click="changeSysInfo('{memberName}')"
            >{{ $t('message.hymc') }}</el-button>
            <el-button
              class="mr10"
              @click="changeSysInfo('{gymName}')"
            >{{ $t('message.cgmc') }}</el-button>
            <el-select v-model="param.addressValue" @change="changeAddress">
              <el-option
                v-for="item in addressOption"
                :key="item.val"
                :label="item.name"
                :value="item.val"
              />
            </el-select>
          </div>
        </el-form-item>
        <el-form-item
          v-if="param.smsType == '1' && param.isSendMsg == '1'"
          style="margin-top: -20px"
        >
          <div class="df_sb">
            <span
              class="placeholder9"
            >{{ $t('message.wfwcn') }}</span>
            <span v-if="param.smsInfo">{{ $t('message.dqygcs') }}{{ smsNum }}{{ $t('message.tdx') }}</span>
          </div>
        </el-form-item>
        <el-form-item>
          <el-button
            v-preventReClick
            :loading="subLoading"
            type="primary"
            @click="onSubmit"
          >{{ $t('message.tj') }}</el-button>
          <el-button @click="handleClose">{{ $t('message.qx') }}</el-button>
        </el-form-item>
      </el-form>
    </el-drawer>
  </div>
</template>

<script>
import MemberSearch from '@/components/MemberSearch'
import {
  portrayalPostList,
  smsSignature,
  smsTemplateList,
  configDictionaries,
  smsTemplateOption,
  couponDirectedAdd,
  couponMealList
} from '@/api'
export default {
  components: {
    MemberSearch
  },
  data() {
    return {
      param: {
        receptionType: '3',
        grantType: '1',
        isSendMsg: '0',
        smsType: '1',
        grantObj: [],
        obj: ''
      },
      subLoading: false,
      portrayalList: [],
      addressList: [],
      rules: {
        receptionType: [{ required: true, message: this.$t('message.qxz'), trigger: 'change' }],
        obj: [{ required: true, message: this.$t('message.qxz'), trigger: 'change' }],
        grantObj: [{ required: true, message: this.$t('message.qxz'), trigger: 'blchangeur' }],
        smsInfo: [{ required: true, message: this.$t('message.qsr'), trigger: 'blur' }],
        smsTempId: [{ required: true, message: this.$t('message.qsr'), trigger: 'blur' }]
      },
      isShowModal: false,

      shopInfo: {},
      smsTemplate: [],
      addressOption: [],

      couponList: [],
      mealList: []
    }
  },
  computed: {
    smsNum() {
      if (this.param.smsInfo) {
        return Math.ceil(this.param.smsInfo.length / 67)
      } else {
        return 0
      }
    }
  },
  created() {
    this.getPortrayalPostList()
    this.changeType('1')
  },
  methods: {
    onSubmit() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          const { param } = this
          const fn = couponDirectedAdd
          this.subLoading = true
          // if (param.smsInfo) {
          //   param.smsInfo = param.smsInfo + ' --{{ $t('message.jsqhfr') }}'
          // }
          fn({ param }).then(res => {
            this.subLoading = false
            this.$message.success(this.$t('message.tjcg'))
            this.handleClose()
            this.$emit('success')
          }, () => {
            this.subLoading = false
          })
        }
      })
    },
    changeReType() {
      this.$set(this.param, 'obj', '')
    },
    portrayalClick(id) {
      this.$set(this.param, 'obj', id)
      this.$refs.form.clearValidate()
    },
    changeSms(val) {
      if (val === '0') {
        this.$set(this.param, 'tempId', '')
      } else {
        this.initSms() // 签名
      }
    },
    changeSysInfo(val) {
      const smsInfo = this.param.smsInfo || ''
      const textareaEle = document.querySelector('#textareaId')
      const startPos = textareaEle.selectionStart
      if (startPos || startPos === 0) {
        const arr = smsInfo.split('')
        arr.splice(startPos, 0, `${val}`)
        this.$set(this.param, 'smsInfo', arr.join(''))
      } else {
        this.$set(this.param, 'smsInfo', smsInfo + `${val}`)
      }
    },
    changeAddress(val) {
      smsTemplateOption({ param: { path: val }}).then(res => {
        this.changeSysInfo(res.record.miniProgramLink)
      })
    },
    changeSmsType(val) {
      if (val === '1') {
        this.$set(this.param, 'smsTempId', '')
      } else {
        this.$set(this.param, 'smsInfo', '')
      }
    },
    changeType(val) {
      if (val === '1') {
        couponMealList({ param: { type: 1 }, userId: sessionStorage.getItem('userId') }).then(res => {
          this.couponList = res.recordList || []
        })
      }
      if (val === '2') {
        couponMealList({ param: { type: 2 }}).then(res => {
          this.mealList = res.recordList || []
        })
      }
      this.$set(this.param, 'grantObj', [])
      //
      //
    },
    getPortrayalPostList() {
      portrayalPostList({ param: {}}).then(res => {
        this.portrayalList = res.recordList || []
      })
    },
    initSms() {
      smsSignature({ param: {}}).then(res => {
        this.shopInfo = res.record
      })
      smsTemplateList({ param: { smsType: '1', smsStatus: '1', smsEnable: '0' }}).then(res => {
        this.smsTemplate = res.recordList
      })
      configDictionaries({ param: { codes: 'WX_URL' }}).then(res => {
        this.addressOption = JSON.parse(res.recordList[0].val)
      })
    },
    handleClose() {
      this.isShowModal = false
      this.$emit('close')
    },
    memberChange(val) {
      this.$set(this.param, 'obj', val.id)
      this.$refs.form.clearValidate()
    },
    memberClear() {
      this.$set(this.param, 'obj', '')
    },
    goToPortrayal() {
      if (this.$route.name === 'Portrayal') {
        this.handleClose()
        this.$emit('openPortrayal')
      } else {
        this.handleClose()
        this.$router.push({
          name: 'Portrayal',
          query: {
            portrayalFlag: '1'
          }
        })
      }
    }
  }
}
</script>

<style lang="scss" scoped>
@import "@/styles/variables.scss";
.portrayal_option {
  background-color: #f1f3f9;
  border-radius: 2px;
  padding: 8px;
  padding-bottom: 40px;
  .list {
    display: flex;
    flex-wrap: wrap;
    margin: 0 -4px;
    .item {
      line-height: 20px;
      margin: 3px 4px;
      padding: 4px 8px;
      border-radius: 4px;
      border: 1px solid #e4e4e4;
      color: #999999;
      cursor: pointer;
    }
    .active {
      border: 1px solid $primaryColor;
      color: $primaryColor;
    }
  }
  .fs12 {
    position: absolute;
    left: 4px;
    bottom: 4px;
    line-height: 16px;
  }
}
.sms_template {
  position: relative;
  .el-textarea {
    padding-bottom: 36px;
  }
  .rr {
    position: absolute;
    left: 4px;
    bottom: 16px;
    line-height: 16px;
  }
}
</style>
